<?php
namespace app\wx\model;
use think\facade\Cache;
use think\Model;
use think\Db;
use Util\Tool;

class Weixin extends Model{
    public function __construct()
    {
        parent::__construct();
        $this->Tool = new Tool();
    }
    //签名校验
    public function valid(){
        file_put_contents('weixinlog.txt',PHP_EOL.json_encode($_GET).PHP_EOL,FILE_APPEND);
        file_put_contents('weixinlog.txt',PHP_EOL.json_encode($_POST).PHP_EOL,FILE_APPEND);
        file_put_contents('weixinlog.txt',PHP_EOL.json_encode(file_get_contents("php://input")).PHP_EOL,FILE_APPEND);
        $signature = input('get.signature');
        $timestamp = input('get.timestamp');
        $nonce = input('get.nonce');
        $echostr = input('get.echostr');
        $token = config('wx.weixintoken');
        $tmpArr = array($timestamp,$nonce,$token);
        sort($tmpArr,SORT_STRING);//对组合的字符串进行排序
        $str = implode( $tmpArr );//将数组合为字符串
        $str = sha1( $str );//将字符串加密
        if($str != $signature){
            return false;
        }
        return true;
    }
    //获取accesstoken
    public function access_token($iscache=true){//设置默认从缓存拿数据
        $key = 'access_token';
        if(!$iscache){//判断$iscache是否需要缓存，如果false就删掉缓存
            Cache::rm($key);
        }
        //判断$data和$iscache，如果都为真则返回缓存数据
        $data = Cache::get($key);
        if($data && $iscache){
            return $data;
        }
        //按照wx规定获取token
        $appid = config('wx.appid');
        $appsecret = config('wx.appsecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//设置抓取的url
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以字符流的形式返回，而不是直接输出
        curl_setopt($ch,CURLOPT_HEADER,0);//是否输出页面内容
        curl_setopt($ch,  CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//抓取页面的等待时间为30秒
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        $res = curl_exec($ch);//执行命令
        if ($res === FALSE){
            echo 'cURL Error:'.curl_error($ch);
        }
        curl_close($ch);//关闭URL请求
        $res = json_decode($res,true);
        //dump($res);
        //判断获取的token是否为空
        if(!isset($res['access_token'])){
            return false;
        }
        Cache::set('access_token',$res['access_token'],$res['expires_in']-600);
        return $res['access_token'];
        //dump($res);exit;
    }

    //网页授权access_token
    public function auth_access_token($code){
        $appid = config('wx.appid');
        $appsecret = config('wx.appsecret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        //echo '网页授权token地址<br>'.$url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//设置抓取的url
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以字符流的形式返回，而不是直接输出
        curl_setopt($ch,CURLOPT_HEADER,0);//是否输出页面内容
        curl_setopt($ch,  CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//抓取页面的等待时间为30秒
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        $res = curl_exec($ch);//执行命令
        if ($res === FALSE){
            echo 'cURL Error:'.curl_error($ch);
            $this->Tool->writeLog(date('Y-m-d-H-i-s',time()).PHP_EOL.var_export($ch,true),'wx_user_code');

        }
        curl_close($ch);//关闭URL请求
        $res = json_decode($res,true);//强制转换为PHP关联数组
        //dump($res);
        $this->Tool->writeLog(date('Y-m-d-H-i-s',time()).PHP_EOL.var_export($res,true),'wx_user_code');
        if(!isset($res['access_token'])){
            dump($res);die;
        }
        return $res;
    }

    // 获取jsapi_ticket
    public function jsapi_ticket($access_token,$iscache = true){
//        $appid = config('app.appid');
//        $appsecret = config('app.appsecret');
//        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
//        $res = http_get($url);
//        dump($res);exit();
        $key = 'jsapi_ticket';
        if(!$iscache){
            Cache::rm($key);
        }
        $data = Cache::get($key);
        if($data && $iscache){
            return $data;
        }
        $appid = config('wx.appid');
        $appsecret = config('wx.appsecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, true);//设置post方式提交
        curl_setopt($ch, CURLOPT_URL, $url);//设置抓取的url
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $returnText);//设置post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以字符流的形式返回，而不是直接输出
        curl_setopt($ch,CURLOPT_HEADER,0);//是否输出页面内容
        curl_setopt($ch,  CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//抓取页面的等待时间为30秒
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        $response = curl_exec($ch);//执行命令
        if ($response === FALSE){
            echo 'cURL Error:'.curl_error($ch);
        }
        curl_close($ch);//关闭URL请求
        $res = json_decode($response,true);
        if(!isset($res['ticket'])){
            return false;
        }
        Cache::set($key,$res['ticket'],($res['expires_in']-100));
        return $res['ticket'];

    }

    // 拉取用户信息
    public function get_userinfo($auth_access_token,$openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$auth_access_token.'&openid='.$openid.'&lang=zh_CN';
        //echo '拉取用户信息回调地址<br>'.$url;
        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, true);//设置post方式提交
        curl_setopt($ch, CURLOPT_URL, $url);//设置抓取的url
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $returnText);//设置post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以字符流的形式返回，而不是直接输出
        curl_setopt($ch,CURLOPT_HEADER,0);//是否输出页面内容
        curl_setopt($ch,  CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//抓取页面的等待时间为30秒
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        $response = curl_exec($ch);//执行命令
        if ($response === FALSE){
            echo 'cURL Error:'.curl_error($ch);
        }
        curl_close($ch);//关闭URL请求
        $res = json_decode($response,true);
        return $res;
    }

    // 被动回复用户图文消息
    public function img_article_msg($data){
        // 数据库读取图文消息
        $articles = array(
            array('title'=>'从php招聘要求看php程序员应该会什么？','description'=>'目前在国内有很多知名公司都采用PHP 作为主要的开发 Web 开发语言，php中文网小编就从专业的IT招聘网站拉钩网挑选几条php招聘要','picurl'=>'http://img.php.cn/upload/article/000/000/164/58a56f51f0d4c979.jpg','url'=>'http://www.php.cn/toutiao-352287.html'),
            array('title'=>'全球php开发框架排行榜','description'=>'在PHP开发中，选择合适的框架有助于加快软件开发，节约宝贵的项目时间，让开发者专注于功能的实现上。由于流行的框架经过了大量项','picurl'=>'http://img.php.cn/upload/article/000/000/002/82ff85191adbac932aec043cbf901727.jpg','url'=>'http://www.php.cn/toutiao-380795.html'),
        );
        // 回复图文消息
        $xml = $this->build_img_text_msg($data['FromUserName'],$data['ToUserName'],$articles);
        return $xml;
    }

    // 附近的店铺[默认附近10公里]
    public function near_shops($from,$to,$distance = 10){
        $user = Db::name('user')->where(array('openid'=>$to))->find();
        $lat = $user['lat'];
        $lng = $user['lng'];
        $res = \think\Db::name('shop')->field('id,title,address,(6371*acos(cos(radians('.$lat.'))*cos(radians(lat))*cos(radians(lng)-radians('.$lng.'))+sin(radians('.$lat.'))*sin(radians(lat)))) AS distance')->having('distance < '.$distance)->order('distance')->select();
        $shop_list = [];
        foreach ($res as $key => $value) {
            $shop_list[] = array('title'=>$value['title'],'description'=>$value['address'].'  距离：'.$value['distance'].'公里','picurl'=>$value['img'],'url'=>'/');
        }
        // 回复图文消息
        $xml = $this->build_img_text_msg($from,$to,$shop_list);
        return $xml;
    }

    /**
     * 构造图文消息
     * $from 谁发的
     * $to 发给谁的
     * $data:发送的数据【title,description,picurl,url】
     */
    private function build_img_text_msg($from,$to,$data){
        file_put_contents('builddata.txt',var_export($data,TRUE).PHP_EOL,FILE_APPEND);
        $str = '<xml><ToUserName>'.$from.'</ToUserName><FromUserName>'.$to.'</FromUserName><CreateTime>'.time().'</CreateTime><MsgType>news</MsgType><ArticleCount>2</ArticleCount><Articles>';
        foreach ($data as $item) {
            $str .= '<item><Title>'.$item['title'].'</Title> <Description>'.$item['description'].'</Description><PicUrl>'.$item['picurl'].'</PicUrl><Url>'.$item['url'].'</Url></item>';
        }
        $str .= '</Articles></xml>';
        file_put_contents('buildurl.txt',$str);
//        return $response = '<xml><ToUserName>'.$from.'</ToUserName>
//        <FromUserName>'.$to.'</FromUserName>
//        <CreateTime>1528269940</CreateTime>
//        <MsgType>text</MsgType>
//        <Content>故障</Content>
//        <MsgId>6563869412233738189</MsgId>
//        </xml>';


        return $str;
    }

    // 关注
    public function subscribe($data){
        file_put_contents("guanzhu.txt", var_export($data,true).PHP_EOL,FILE_APPEND);
        // 检查用户是否已存在
        $user = Db::name('user')->where(array('openid'=>$data['FromUserName']))->find();
        if(!$user){
            Db::name('user')->insertGetId(array('openid'=>$data['FromUserName'],'sub_status'=>1,'add_time'=>time()));
            $wellcome = '<xml> <ToUserName>'.$data['FromUserName'].'</ToUserName> <FromUserName>'.$data['ToUserName'].'</FromUserName> <CreateTime>1566975737</CreateTime> <MsgType>text</MsgType> <Content>一点都不好</Content> </xml>';
            return $wellcome;
        }else{
            Db::name('user')->where(array('openid'=>$data['FromUserName']))->update(array('sub_status'=>1));
        }die;
    }

    // 取消关注
    public function unsubscribe($data){
        file_put_contents("guanzhu.txt", var_export($data,true).PHP_EOL,FILE_APPEND);
        Db::name('user')->where(array('openid'=>$data['FromUserName']))->update(array('sub_status'=>0));
    }

    // 定位
    public function location($data){
        Db::name('user')->where(array('openid'=>$data['FromUserName']))->update(array('lat'=>$data['Latitude'],'lng'=>$data['Longitude']));
    }

    // 机器人聊天
    public function robot($data){
        $config = config('wx.robot');
        $params['appid'] = $config['appid'];
        $key = $config['key'];
        $params['timestamp'] = time();
        $params['msg'] = $data['Content'];
        ksort($params);//按照键名对关联数组进行升序排序
        $str = http_build_query($params);//将数组$params进行拼装，类似foo=bar&baz=boom&cow=milk&php=hypertext+processor
        $sign = sha1($str.$key);//将$str.$key进行sha1加密
        $url = 'http://www.php.cn/index.php/weixintest/robot?'.$str.'&sign='.$sign;
        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_POST, true);//设置post方式提交
        curl_setopt($ch, CURLOPT_URL, $url);//设置抓取的url
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $returnText);//设置post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以字符流的形式返回，而不是直接输出
        curl_setopt($ch,CURLOPT_HEADER,0);//是否输出页面内容
        curl_setopt($ch,  CURLOPT_FOLLOWLOCATION, 1); // 302 redirect
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);//抓取页面的等待时间为30秒
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        $response = curl_exec($ch);//执行命令
        if ($response === FALSE){
            echo 'cURL Error:'.curl_error($ch);
        }
        curl_close($ch);//关闭URL请求
        $res = json_decode($response,true);//对JSON解码，当第二个参数为 TRUE 时，将返回 array 而非 object 。
        $res['msg'] = str_replace('{br}', "\n", $res['msg']);
        $response = '<xml> <ToUserName>'.$data['FromUserName'].'</ToUserName> <FromUserName>'.$data['ToUserName'].'</FromUserName> <CreateTime>'.time().'</CreateTime> <MsgType>text</MsgType> <Content>'.$res['msg'].'</Content> </xml>';
        file_put_contents('robot.txt',PHP_EOL.$url.PHP_EOL.$response.PHP_EOL,FILE_APPEND);
        return $response;
    }
    
    public function get_location_address($lat,$lng){
    	$host = "https://regeo.market.alicloudapi.com";
		$path = "/v3/geocode/regeo";
		$method = "GET";
		$appcode = "b6896f4c1b1e4eaa8a7491291c39f1ed";
		$headers = array();
		array_push($headers, "Authorization:APPCODE " . $appcode);
		$querys = "batch=true&callback=callback&extensions=all&homeorcorp=all&location=".$lng.",".$lat."6&output=json&radius=1000&roadlevel=all";
		$bodys = "";
		$url = $host . $path . "?" . $querys;
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_FAILONERROR, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HEADER, false);
		if (1 == strpos("$".$host, "https://"))
		{
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		}
		$res = curl_exec($curl);
		curl_close($curl);
		echo '<pre>';
		$res = str_replace("callback(","",$res);
		$res = str_replace(")","",$res);
		$res = json_decode($res,true);
		// var_dump($res['status']==1);
		// var_dump($res['info']=='OK');
		// var_dump($res['infocode']==10000);
		if($res['status']==1&&$res['info']=='OK'&&$res['infocode']==10000){
		//    var_dump($res);
		//    var_dump($res['regeocodes']['0']['addressComponent']);
		    $country = $res['regeocodes']['0']['addressComponent']['country'];
		    $province = $res['regeocodes']['0']['addressComponent']['province'];
		    $city = $res['regeocodes']['0']['addressComponent']['city'];
		    $citycode = $res['regeocodes']['0']['addressComponent']['citycode'];
		    $district = $res['regeocodes']['0']['addressComponent']['district'];
		    $adcode = $res['regeocodes']['0']['addressComponent']['adcode'];
		    $township = $res['regeocodes']['0']['addressComponent']['township'];
		    $towncode = $res['regeocodes']['0']['addressComponent']['towncode'];
		    $street = $res['regeocodes']['0']['addressComponent']['streetNumber']['street'];
		    $number = $res['regeocodes']['0']['addressComponent']['streetNumber']['number'];
		    $location = $res['regeocodes']['0']['addressComponent']['streetNumber']['location'];
		    $direction = $res['regeocodes']['0']['addressComponent']['streetNumber']['direction'];
		    $distance = $res['regeocodes']['0']['addressComponent']['streetNumber']['distance'];
		    echo $country.$province.$city.$district.$township.$street.'附近暂无房源';
		}
    }

    public function send_user_msg(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        //dump($access_token);die;
        //2.组装群发预览接口数据  array
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$access_token;
        $array =[
            'touser'=> 'oPcHts09eGE37JdN2eEo9Dy76kL0',        //openid
            'text'  => ['content' => '雨纷纷，旧故里草木深sssssss'],                //文本内容
            'msgtype' => 'text'                                //格式
        ];
        //3.将数组转成json格式
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        //echo $url;die;
        //$this->curl_get();
        //4.调用第三方接口
        $res = $this->Tool->curl( $url,$postJson);
        return json_decode($res,true);
    }

    public function send_user_qun(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        //dump($access_token);die;
        //2.组装群发预览接口数据
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=".$access_token;
        $array =[
            'filter'=> [
                "is_to_all"=>false,
                "tag_id"=>2
            ],        //openid
            'text'  => ['content' => '雨纷纷，旧故里草木深'],                //文本内容
            'msgtype' => 'text',
            "send_ignore_reprint"=>0
        ];
        //3.将数组转成json格式
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        //echo $url;die;
        //$this->curl_get();

        //4.调用第三方接口
        $res = $this->Tool->curl( $url ,$postJson);
        return json_decode($res,true);

    }

    //获取所有用户openid
    public function wx_group(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token;
        $res = $this->Tool->curl( $url);
        return json_decode($res,true);

    }

    //添加wx群发分组3
    public function wx_tags($name){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=".$access_token;
        $array =array(
            'tag'	=>	[
                'name'	=>	$name,
            ]
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url ,$postJson);
        return json_decode($res,true);

    }


    //查询wx群发分组
    public function wx_check_tags(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=".$access_token;
        $res = $this->Tool->curl( $url );
        return json_decode($res,true);

    }

    //修改wx群发分组
    public function wx_modify_tags(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token=".$access_token;
        $array =array(
            'tag'	=>	[
                'id'	=>	'100',
                'name'	=>	'mmm',
            ]
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $postJson);
        return json_decode($res,true);

    }

    //删除wx群发分组
    public function wx_delete_tags($id){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=".$access_token;
        $array =array(
            'tag'	=>	[
                'id'	=>	$id,
            ]
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $postJson);
        return json_decode($res,true);

    }

    //获取wx群发分组粉丝列表
    public function wx_tags_get(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=".$access_token;
        $array =array(
            'tagid'	=>	'2',
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $postJson);
        return json_decode($res,true);

    }

    //给粉丝添加标签
    public function wx_tags_add(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=".$access_token;
        $array =array(
            'tagid'			=>	'2',
            'openid_list'	=>	[
                'oPcHts09eGE37JdN2eEo9Dy76kL0',
                'oPcHts-_eGwQHBcMlcABEtEA-aEU',
            ]
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $postJson);
        return json_decode($res,true);

    }

    //给粉丝删除标签
    public function wx_tags_del(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token=".$access_token;
        $array =array(
            'tagid'			=>	'2',
            'openid_list'	=>	[
                'oPcHts09eGE37JdN2eEo9Dy76kL0',
                'oPcHts-_eGwQHBcMlcABEtEA-aEU',
            ]
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $postJson);
        return json_decode($res,true);

    }

    //获取粉丝标签
    public function wx_tags_getidlist(){
        //1.获取全局access_token
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=".$access_token;
        $array =array(
            'openid'			=>	'oPcHts09eGE37JdN2eEo9Dy76kL0',
        );
        $postJson = json_encode($array,JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $postJson);
        return json_decode($res,true);

    }


    //获取accesstoken
    public function get_access_token(){
        $cache_token = 'access_token';
        $access_token = Cache::get($cache_token);
        if($access_token){
            return $access_token;
        }else{
            $iscache=true;
            return $this->access_token($iscache);
        }
    }

    public function seng_user_msg($openid,$msg='Hello World'){
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
        $json = json_encode(array('touser'=>$openid,'msgtype'=>'text','text'=>['content'=>$msg]),JSON_UNESCAPED_UNICODE);
        $res = $this->Tool->curl( $url, $json);
        json_decode($res,true);
        dump($res);
    }


}